package com.coy.web.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.session.web.http.HeaderHttpSessionIdResolver;
import org.springframework.session.web.http.HttpSessionIdResolver;

/**
 * 启用基于redis的Spring Session，该配置bean会创建springSessionRepositoryFilter
 * <p>
 * spring-session配置：
 * 基于application.properties中的属性配置(相当于手动添加@EnableRedishttpsession注释)
 * <code>
 * # session存储类型
 * spring.session.store-type=redis
 * # 设置session超时时间
 * server.session.timeout=2000
 * # 刷新数据模式，on-save响应返回时把session刷新到redis， immediate马上刷新到redis
 * spring.session.redis.flush-mode=on-save
 * # redis session key命名空间
 * spring.session.redis.namespace=coy
 * </code>
 */
@Configuration
public class RedisHttpSessionConfig {

    /**
     * sessionId写入Headers中的key，默认为x-auth-token
     */
    @Value("${spring.session.headerName}")
    String sessionHeaderName;

    public String getSessionHeaderName() {
        return sessionHeaderName;
    }

    /**
     * 自定义HttpSession的策略（支持将sessionId写入到cookie和header两种方式，默认为cookie）
     */
    @Bean
    public HttpSessionIdResolver httpSessionStrategy() {
        HeaderHttpSessionIdResolver httpSessionStrategy = new HeaderHttpSessionIdResolver(sessionHeaderName);
        return httpSessionStrategy;
    }

    /**
     * 指定session的序列化方式(比默认的jdk序列化速度要快)
     */
    @Bean
    public RedisSerializer springSessionDefaultRedisSerializer() {
        return new Jackson2JsonRedisSerializer<>(Object.class);
    }

}
